package com.planet.api;


import com.planet.facade.UserBiz;
import com.planet.query.UserQuery;
import com.planet.utils.AssertUtils;
import com.planet.utils.UtilTools;
import com.planet.utils.global.ExceptionHandle;
import com.planet.utils.global.Result;
import com.planet.utils.global.ResultUtil;
import com.planet.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created by jiayazi on 17/11/13.
 */
@Api("用户登陆等")
@RestController
@RequestMapping("nb/api/user")
public class UserAPI {
    private static final Logger LOGGER = LogManager.getLogger(UserAPI.class);

    @Autowired
    private ExceptionHandle exceptionHandle;
    @Autowired
    private UserBiz userBiz;


    /**
     * 登陆
     * @param userName 用户Id
     * @return
     */
    @GetMapping("/login")
    @ApiOperation(value = "登陆")
    public Result login(@ApiParam(name = "userName") @RequestParam String userName,@ApiParam(name = "passWord") @RequestParam String passWord){

        //默认结果是成功的
        Result result = ResultUtil.success();
        try {
            String userId = userBiz.login(userName,passWord);
            if (StringUtils.isEmpty(userId)){
                result =  ResultUtil.error(1,"用户名或密码错误");
                return result;
            }

            UserVO userVO = userBiz.selectByPrimaryKey(userId);
            result =  ResultUtil.success(userVO);

        }catch (Exception e){
            //调用异常工具类，统一处理异常
            result =  exceptionHandle.exceptionGet(e);
        }
        return result;
    }



    /**
     * 注册
     * @param userQuery 用户Id
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册")
    public Result register(@ApiParam("注册信息  login_time要是手机号") UserQuery userQuery){

        AssertUtils.isNotNull(userQuery.getLogin_name(),"登陆名不能为空");
        AssertUtils.isNotNull(userQuery.getPass_word(),"密码不能为空");
        //默认结果是成功的
        Result result = ResultUtil.success();
        try {
            String registerState = userBiz.checkUserName(userQuery.getLogin_name());
            if (StringUtils.isNotBlank(registerState)){
                result = ResultUtil.error(1,"用户名已存在");
                return result;
            }

            userQuery.setUserId(UtilTools.getUserId());
            userBiz.insertSelective(userQuery);
            result = ResultUtil.success(0,"注册成功");
        }catch (Exception e){
            //调用异常工具类，统一处理异常
            result =  exceptionHandle.exceptionGet(e);
        }
        return result;
    }

}
